<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018\7\17 0017
 * Time: 11:29
 */
namespace model;
use model;
class cartModel extends model{



    public static function get_list( $user_id, $cart_ids ){

        $sql = "SELECT c.*, g.price, g.name FROM sh_cart c  LEFT JOIN sh_goods g  ON c.goods_id = g.`id` ".
                " where user_id=" . $user_id;

        $where_id = [];
        if( !empty( $cart_ids ) ){
            foreach( $cart_ids as $cart_id ){
                $where_id[] = 'c.id='. $cart_id;
            }
            $sql .= ' and ( ' .implode( ' or ', $where_id) . ') ';
        }

        $result = self::$db->query( $sql );


        return $result->rows;

    }


    public static function filter( $user_id, $cart_ids ){

        $sql = "SELECT c.*, g.price, g.name FROM sh_cart c  LEFT JOIN sh_goods g  ON c.goods_id = g.`id` ".
            " where user_id=" . $user_id;
        $result = self::$db->query( $sql );


        return $result->rows;

    }

    public static function add( $product_id, $number, $user_id ){

        $sql = 'SELECT * FROM sh_cart WHERE user_id=' . $user_id .' and goods_id=' . $product_id;

        $result = self::$db->query( $sql );

        $cart_sql = '';
        if( !empty( $result->row) ){
            $number = $result->row['goods_num'] + 1;
            $cart_sql = 'update sh_cart set user_id='. $user_id
                .',goods_id=' . $product_id
                .',goods_num=' . $number
                .' where id=' . $result->row['id']
            ;
        }else{
            $cart_sql = 'insert into sh_cart set user_id='. $user_id
                .',goods_id=' . $product_id
                .',goods_num=' . $number;
        }

        self::$db->query( $cart_sql );


    }

    public static function change( $cart_id, $number ){

        $sql = "update sh_cart set goods_num=". $number . " where id=" . $cart_id;
        $res = self::$db->query( $sql );
        return $res;
    }

    public static function remove( $cart_id ){

        $sql = 'delete from sh_cart where id=' . $cart_id;

        $res = self::$db->query( $sql );

        return $res;
    }

    public static function removeMore( $cart_ids ){

        $in_values = implode(',',$cart_ids );

        $sql = "delete from sh_cart where id in(" . $in_values . ")";

        $res = self::$db->query( $sql );

        return $res;
    }


}